package com.abocode.aichat.server.delivery.inbound;


import com.abocode.aichat.server.delivery.AbstractServerDeliver;
import com.abocode.aichat.server.delivery.RelayResult;
import com.abocode.aichat.server.entity.Entity;
import com.abocode.aichat.server.reply.Replies;
import com.abocode.aichat.server.reply.Reply;
import com.abocode.aichat.server.stanza.Stanza;
import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * Created by franky-8.
 */
public class InboundServerDeliver extends AbstractServerDeliver<Replies> {

    private static Log log= LogFactory.getLog(InboundServerDeliver.class);

    class InboundReplyCallable implements Callable<RelayResult> {
//        private ServerRuntimeContext serverRuntimeContext;

        public Channel channel;

        public Stanza stanza;

        public InboundReplyCallable(Channel channel, Stanza stanza) {
            this.channel = channel;
            this.stanza = stanza;
//            this.serverRuntimeContext = serverRuntimeContext;
        }

        @Override
        public RelayResult call() throws Exception {
            try {
                String replyStr = JSON.toJSONString(stanza);
                Entity entity = stanza.findTo();
                if (entity != null) {
                    String domain = getServerRuntimeContext().getProtocolChannelRegistry().domain(entity);
                    log.info("domain:"+domain+"replyStr:"+replyStr);
                    if (domain!=null && !getServerRuntimeContext().validateDomain(domain)) {
                        getServerRuntimeContext().getMessageGatewayPipeline().sendMessageToChannel(replyStr, domain);
                    }else{
                        channel.writeAndFlush(replyStr).sync();
                    }
                }else{
                    channel.writeAndFlush(replyStr).sync();
                }
            } catch (Exception ex) {
                return new RelayResult("fail", 500);
            }
            return new RelayResult("succ", 200);
        }
    }

    @Override
    public void deliver(Replies replies, Stanza stanza) {
        if (replies == null) {
            return;
        }
        for (Reply reply : replies.getReplies()) {
            for (Channel channel : reply.getChannels()) {
                if (reply.getStanza() != null) {
                    Future<RelayResult> future = executor.submit(new InboundReplyCallable(channel, reply.getStanza()));
                } else {
                    //todo
                }
            }
        }
    }

}
